/**
 * 
 */
package com.ginger.sms;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @Description: 发送短信验证码实例
 * @author 姜锋
 * @date 2018年8月12日 下午9:39:54
 * @version V1.0
 */
public class APITest {
	private static String SECRET_ID = "SECRET_ID";
	/**
	 * 腾讯云交易key 必填项
	 */
	private static String SECRET_KEY = "SECRET_KEY";

	public static void main(String[] args) throws Exception {
		/**
		 * api发送接口 必填项
		 */
		String host = "http://api.justginger.top";
		String path = "/user/1";
		String url = host + path;
		/**
		 * httpClient4.2.4及以上版本
		 */
		HttpClient httpClient = new DefaultHttpClient();
		// get method
		HttpPost httpPost = new HttpPost(url);
		Date date = new Date();
		httpPost.setHeader("Date", gmtTIME(date));
		String timeStr = "date: " + gmtTIME(date);
		String sign = hmacSHA1Encrypt(timeStr, SECRET_KEY);
		String authStr = "hmac id=\"" + SECRET_ID + "\",algorithm=\"hmac-sha1\",headers=\"date\", signature=\"" + sign
				+ "\"";
		httpPost.addHeader("Authorization", authStr);
		// response
		HttpResponse response = null;
		try {
			response = httpClient.execute(httpPost);
		} catch (Exception e) {
		}
		// get response into String
		String temp = "";
		try {
			HttpEntity entity = response.getEntity();
			temp = EntityUtils.toString(entity, "UTF-8");
			ObjectMapper mapper = new ObjectMapper();
			User sMSObject = mapper.readValue(temp, User.class);
			// 输出返回值
			System.out.println(temp);
			System.out.println(sMSObject);
		} catch (Exception e) {
		}
	}
	/**
	 * HmacSHA1加密
	 * @param encryptText 加密字符串
	 * @param encryptKey 加密key
	 * @return
	 * @throws Exception
	 */
	private static String hmacSHA1Encrypt(String encryptText, String encryptKey) throws Exception {
		byte[] data = encryptKey.getBytes("UTF-8");
		// 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
		SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
		// 生成一个指定 Mac 算法 的 Mac 对象
		Mac mac = Mac.getInstance("HmacSHA1");
		// 用给定密钥初始化 Mac 对象
		mac.init(secretKey);
		byte[] text = encryptText.getBytes("UTF-8");
		// 完成 Mac 操作,base64编码
		String sign = Base64.encodeBase64String(mac.doFinal(text));
		return sign;
	}
	/**
	 * 获得格林威治时间
	 * @param date 时间
	 * @return
	 */
	private static String gmtTIME(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
		// 设置时区为GMT
		sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
		String time = sdf.format(date.getTime());
		return time;
	}
}
